package com.cy.dao.impl;

import com.cy.dao.NoticesJdbc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class NoticesJdbcImpl implements NoticesJdbc {
    @Autowired
    private DataSource dataSource;

    @Override
    public void saveNotice(String sql, Object[] values) throws SQLException {
        Connection connection = dataSource.getConnection();

        PreparedStatement stmt = connection.prepareStatement(sql);
        for (int i = 0; i < values.length; i++) {
            stmt.setObject(i + 1, values[i]);
        }
        stmt.execute();

        stmt.close();
        connection.close();
    }

    @Override
    public List<Map<String, Object>> selectNotices(String sql, Object[] values) throws SQLException {
        Connection connection = dataSource.getConnection();

        PreparedStatement pre = connection.prepareStatement(sql);
        pre.setInt(1, 2);
        boolean flag = pre.execute();
        ResultSet res = null;
        List<Map<String, Object>> list = new ArrayList<>();
        if (flag) {
            res = pre.getResultSet();

            ResultSetMetaData rsmd = res.getMetaData();
            while (res.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {//循环一次取一个字段的值
                    map.put(rsmd.getColumnLabel(i), res.getObject(rsmd.getColumnLabel(i)));
                }
                System.out.println(map);
                list.add(map);
            }
        }
        res.close();
        pre.close();
        connection.close();
        return list;
    }
}
